package com.atguigu.gulimallssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {

    /**
     * 无面登录就可访问
     * @return
     */
    @Value("${sso.server.url}")
    String ssoServerUrl;
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    /**
     * 感知这次是在登录成功返回的。
     * @param model
     * @param session
     * token:只要去ssoserver登录成功就会带回来
     * @return
     */
    @GetMapping("/employees")
    public String employees(Model model, HttpSession session,@RequestParam(value ="token",required = false) String token){

        if (!StringUtils.isEmpty(token)){
            //TODO:1.去ssoserver获取当前token对应的用户的信息
            //此处不远程调用是考试到其他语言没有OPENFeigh
            RestTemplate restTemplate=new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String body=forEntity.getBody();
            session.setAttribute("loginUser",body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser==null){
            //未登录，先去登录,回调地址：redirect_url=http://client1.com:8080/employees
            return "redirect:"+ssoServerUrl+"?redirect_url=http://client1.com:8081/employees";
        }else {
            List<String> emps=new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps",emps);
            return "list";
        }
        

    }

}
